﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using Hxsoft.AppV1;

namespace Hxsoft.AppV1.Module
{
	public partial class TeamBlack : ICreator { }
	public partial class TeamBlack : IOwner
	{
		public Guid? OwnerId
		{
			get {
				GenericModuleDataContext dc = new GenericModuleDataContext();
				dc.ObjectTrackingEnabled = false;
				if (dc.TeamMembers.Exists(this.TeamId))
					return dc.TeamMembers.First(p => p.IsLeader && p.TeamId == this.TeamId).UserId;
				return null;
			}
		}
	}



	/// <summary>
	/// TeamBlacks 类。
	/// </summary>
	public static partial class TeamBlacks
	{
		public const string INFO_TYPE = "TeamBlack";		// 信息的类别代码

		#region GetItem
		/// <summary>
		/// 根据标识获取指定的TeamBlacks。
		/// </summary>
		/// <param name="o">TeamBlacks集合。</param>
		/// <param name="teamId">获取的TeamBlacks标识 TeamId。</param>
		/// <returns>获取的信息项。</returns>
		public static TeamBlack GetItem(this System.Data.Linq.Table<TeamBlack> o, int teamId)
		{
			return o.SingleOrDefault(p => p.TeamId == teamId);
		}

		/// <summary>
		/// 根据标识获取指定的TeamBlacks。
		/// </summary>
		/// <param name="teamId">获取的TeamBlacks标识 TeamId。</param>
		/// <returns>获取的信息项。</returns>
		public static TeamBlack GetItem(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;
			return dc.TeamBlacks.GetItem(teamId);
		}

		#endregion

		#region Exists
		/// <summary>
		/// 验证指定的TeamBlacks是否已经存在。
		/// </summary>
		/// <param name="o">TeamBlacks集合。</param>
		/// <param name="teamId">验证的TeamBlacks标识 TeamId。</param>
		/// <returns>布尔值表示指定的TeamBlacks是否已经存在。</returns>
		public static bool Exists(this System.Data.Linq.Table<TeamBlack> o, int teamId)
		{
			return o.Any(p => p.TeamId == teamId);
		}

		/// <summary>
		/// 验证指定的TeamBlacks是否已经存在。
		/// </summary>
		/// <param name="teamId">验证的TeamBlacks标识 TeamId。</param>
		/// <returns>布尔值表示指定的TeamBlacks是否已经存在。</returns>
		public static bool Exists(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;
			return dc.TeamBlacks.Exists(teamId);
		}


		public static bool Exists(this System.Data.Linq.Table<TeamBlack> o, string teamName)
		{
			return o.Any(p => p.TeamName == teamName);
		}

		public static bool Exists(string teamName)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;
			return dc.TeamBlacks.Exists(teamName);
		}

		private static bool ExistsParent(this System.Data.Linq.Table<TeamBlack> o, int teamId)
		{
			return o.Any(p => p.PTeamId.Value == teamId);
		}

		public static bool ExistsParent(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;
			return dc.TeamBlacks.ExistsParent(teamId);
		}



		#endregion
	}



	/// <summary>
	/// TeamBlacks 类操作部分。
	/// </summary>
	public static partial class TeamBlacks
	{
		#region Insert
		/// <summary>
		/// 添加TeamBlacks。
		/// </summary>
		/// <param name="insertedTeamBlack">添加的TeamBlacks。</param>
		/// <returns>添加的TeamBlacks。</returns>
		public static TeamBlack Insert(TeamBlack insertedTeamBlack)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = insertedTeamBlack.ToNewEntity<TeamBlack>();
			teamBlack.CreatorId = Users.CurrentUserId;
			teamBlack.CreateDate = DateTime.Now;
			teamBlack.IsDelete = false;
			teamBlack.IsEffective = true;

			GetInsertRight(dc, teamBlack, true);	// 权限验证

			dc.TeamBlacks.InsertOnSubmit(teamBlack);
			dc.SubmitChanges();
			
			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Insert, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.Insert.ToString(), teamBlack.TeamName);

			// 返回只读数据
			return insertedTeamBlack.FillByEntity(teamBlack);
		}
		#endregion



		#region Update
		private static readonly HashSet<string> _updatedExcludeColumns = typeof(TeamBlack).GetEntityColumnNames(new string[] {
				"TeamId",
				"IsEffective",
				"IsDelete",
				"CreateDate",
				"CreatorId",
				"SiteId"
				// 在这里填写更新的排除列
			}, true);

		/// <summary>
		/// 修改TeamBlacks。
		/// </summary>
		/// <param name="updatedTeamBlack">修改的TeamBlacks。</param>
		/// <returns>修改的TeamBlacks。</returns>
		public static TeamBlack Update(TeamBlack updatedTeamBlack)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(updatedTeamBlack.TeamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetUpdateRight(dc, teamBlack, true);	// 权限验证

			teamBlack.FillByEntity(updatedTeamBlack, EntityColumnsSetType.Exclude, _updatedExcludeColumns);

			try
			{
				dc.SubmitChanges(ConflictMode.ContinueOnConflict);
			}
			catch (ChangeConflictException e)
			{
				foreach (ObjectChangeConflict occ in dc.ChangeConflicts)
				{
					occ.Resolve(RefreshMode.KeepCurrentValues);
				}
			}			

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Update, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.Update.ToString(), teamBlack.TeamName);

			// 返回只读数据
			return updatedTeamBlack.FillByEntity(teamBlack);
		}
		#endregion



		#region Setting
		private static readonly HashSet<string> _settingColumns = typeof(TeamBlack).GetEntityColumnNames(new string[] {
				"IsEffective",
				"IsDelete"
				// 在这里填写设置的列
			}, true);

		/// <summary>
		/// 设置TeamBlacks。
		/// </summary>
		/// <param name="settedTeamBlack">设置的TeamBlacks。</param>
		/// <returns>设置的TeamBlacks。</returns>
		public static TeamBlack Setting(TeamBlack settedTeamBlack)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(settedTeamBlack.TeamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetSettingRight(dc, teamBlack, true);	// 权限验证

			teamBlack.FillByEntity(settedTeamBlack, _settingColumns);

			try
			{
				dc.SubmitChanges(ConflictMode.ContinueOnConflict);
			}
			catch (ChangeConflictException e)
			{
				foreach (ObjectChangeConflict occ in dc.ChangeConflicts)
				{
					occ.Resolve(RefreshMode.KeepCurrentValues);
				}
			}

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Setting, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.Setting.ToString(), teamBlack.TeamName);

			// 返回只读数据
			return settedTeamBlack.FillByEntity(teamBlack);
		}
		#endregion



		#region SetEffectiveState
		/// <summary>
		/// 设置TeamBlacks的有效状态。
		/// </summary>
		/// <param name="teamId">设置的TeamBlacks标识 TeamId。</param>
		public static void SetEffectiveState(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(teamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetSetEffectiveStateRight(dc, teamBlack, true);	// 权限验证

			teamBlack.IsEffective = !teamBlack.IsEffective;
			try
			{
				dc.SubmitChanges(ConflictMode.ContinueOnConflict);
			}
			catch (ChangeConflictException e)
			{
				foreach (ObjectChangeConflict occ in dc.ChangeConflicts)
				{
					occ.Resolve(RefreshMode.KeepCurrentValues);
				}
			}

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Setting, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.Setting.ToString() + "/EffectiveState", teamBlack.TeamName);
		}

		/// <summary>
		/// 设置TeamBlacks的有效状态。
		/// </summary>
		/// <param name="teamId">设置的TeamBlacks标识 TeamId。</param>
		/// <param name="state">设置的状态。</param>
		public static void SetEffectiveState(int teamId, bool state)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(teamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetSetEffectiveStateRight(dc, teamBlack, true);	// 权限验证

			if (teamBlack.IsEffective == state)
				return;

			teamBlack.IsEffective = state;
			try
			{
				dc.SubmitChanges(ConflictMode.ContinueOnConflict);
			}
			catch (ChangeConflictException e)
			{
				foreach (ObjectChangeConflict occ in dc.ChangeConflicts)
				{
					occ.Resolve(RefreshMode.KeepCurrentValues);
				}
			}

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Setting, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.Setting.ToString() + "/EffectiveState", teamBlack.TeamName);
		}
		#endregion

		/// <summary>
		/// 设置团队队长
		/// </summary>
		/// <param name="teamId"></param>
		/// <param name="userId"></param>
		/// <returns></returns>
		public static string SetGroupLeader(int teamId, Guid userId)
		{
			if (GetSettingRight(GetItem(teamId)))
			{
				try
				{
					if (TeamMembers.Exists(teamId))
					{
						var oldleader = TeamMembers.GetLeader(teamId);
						oldleader.IsLeader = false;
						TeamMembers.Update(oldleader);
					}
				}
				catch {
				}

				if (TeamMembers.Exists(teamId, userId))
				{
					var leader = TeamMembers.GetItem(teamId, userId);
					leader.IsLeader = true;
					TeamMembers.Update(leader);
				}
				return null;
			}
			else
				return string.Format(@"没有设置团队{0}的权限!", teamId);
		}



		#region MarkDeleted
		/// <summary>
		/// 删除TeamBlacks。
		/// </summary>
		/// <param name="teamId">删除的TeamBlacks标识 TeamId。</param>
		public static void MarkDeleted(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(teamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetMarkDeletedRight(dc, teamBlack, true);	// 权限验证

			teamBlack.IsDelete = true;

			dc.SubmitChanges();

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.MarkDeleted, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.MarkDeleted.ToString(), teamBlack.TeamName);
		}
		#endregion



		#region Recover
		/// <summary>
		/// 恢复TeamBlacks。
		/// </summary>
		/// <param name="teamId">恢复的TeamBlacks标识 TeamId。</param>
		public static void Recover(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(teamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetMarkDeletedRight(dc, teamBlack, true);	// 权限验证

			teamBlack.IsDelete = false;

			dc.SubmitChanges();

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.MarkDeleted, INFO_TYPE, teamBlack.TeamId.ToString(), "Recover", teamBlack.TeamName);
		}
		#endregion



		#region Delete
		/// <summary>
		/// 删除TeamBlacks。
		/// </summary>
		/// <param name="teamId">删除的TeamBlacks标识 TeamId。</param>
		public static void Delete(int teamId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			TeamBlack teamBlack = dc.TeamBlacks.GetItem(teamId);
			if (teamBlack == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetDeleteRight(dc, teamBlack, true);	// 权限验证

			Delete(dc, teamBlack);

			dc.SubmitChanges();

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Delete, INFO_TYPE, teamBlack.TeamId.ToString(), PermissionCode.Delete.ToString(), teamBlack.TeamName);
		}

		#region internal Delete
		internal static void Delete(GenericModuleDataContext dc, TeamBlack teamBlack)
		{
			TeamMembers.DeleteByParent(dc, teamBlack);

			if (teamBlack.Parent != null)
				teamBlack.Parent.ChildrenCount -= 1;

			DeleteByParent(dc, teamBlack);
			dc.TeamBlacks.DeleteOnSubmit(teamBlack);			
		}

		internal static void DeleteByParent(GenericModuleDataContext dc, TeamBlack parent)
		{
			IEnumerable<TeamBlack> e = parent.Children.AsEnumerable();
			foreach (TeamBlack i in e)
				Delete(dc, i);
		}
		
		#endregion
		#endregion
	}



	/// <summary>
	/// TeamBlacks 类对应操作权限部分。
	/// </summary>
	public static partial class TeamBlacks
	{
		#region GetInsertRight
		/// <summary>
		/// 获取当前用户是否有添加TeamBlacks的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="teamBlack">添加的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有添加TeamBlacks的权限。</returns>
		public static bool GetInsertRight(GenericModuleDataContext dc, TeamBlack teamBlack, bool triggerException)
		{
			string userName = Users.CurrentUserName;
			int permissionCode = (int)PermissionCode.Insert;
			bool b = dc.AccessController.GetUserIsHasPermission<TeamBlack>(userName, teamBlack, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, teamBlack, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有添加TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">添加的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有添加TeamBlacks的权限。</returns>
		public static bool GetInsertRight(TeamBlack teamBlack, bool triggerException)
		{
			return GetInsertRight(new GenericModuleDataContext(), teamBlack, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有添加TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">添加的TeamBlacks对象。</param>
		/// <returns>布尔值表示当前用户是否有添加TeamBlacks的权限。</returns>
		public static bool GetInsertRight(TeamBlack teamBlack)
		{
			if (Users.CurrentUserId.HasValue)
			{
				int total = 0;
				var oprate = GetOperationRight(teamBlack.TeamId, Users.CurrentUserId.Value, ref total);
				if (total > 0)
					return oprate;
			}

			return GetInsertRight(teamBlack, false);
		}
		#endregion



		#region GetUpdateRight
		/// <summary>
		/// 获取当前用户是否有更新TeamBlacks的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="teamBlack">更新的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有更新TeamBlacks的权限。</returns>
		public static bool GetUpdateRight(GenericModuleDataContext dc, TeamBlack teamBlack, bool triggerException)
		{
			string userName = Users.CurrentUserName;
			int permissionCode = (int)PermissionCode.Update;
			bool b = dc.AccessController.GetUserIsHasPermission<TeamBlack>(userName, teamBlack, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, teamBlack, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有更新TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">更新的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有更新TeamBlacks的权限。</returns>
		public static bool GetUpdateRight(TeamBlack teamBlack, bool triggerException)
		{
			return GetUpdateRight(new GenericModuleDataContext(), teamBlack, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有更新TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">更新的TeamBlacks对象。</param>
		/// <returns>布尔值表示当前用户是否有更新TeamBlacks的权限。</returns>
		public static bool GetUpdateRight(TeamBlack teamBlack)
		{
			if (Users.CurrentUserId.HasValue)
			{
				int total = 0;
				var oprate = GetOperationRight(teamBlack.TeamId, Users.CurrentUserId.Value, ref total);
				if (total > 0)
					return oprate;
			}
			return GetUpdateRight(teamBlack, false);
		}
		#endregion
		
		#region GetMarkDeletedRight
		/// <summary>
		/// 获取当前用户是否有标记删除TeamBlacks的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="teamBlack">标记删除的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有标记删除TeamBlacks的权限。</returns>
		public static bool GetMarkDeletedRight(GenericModuleDataContext dc, TeamBlack teamBlack, bool triggerException)
		{
			string userName = Users.CurrentUserName;
			int permissionCode = (int)PermissionCode.MarkDeleted;
			bool b = dc.AccessController.GetUserIsHasPermission<TeamBlack>(userName, teamBlack, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, teamBlack, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有标记删除TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">标记删除的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有标记删除TeamBlacks的权限。</returns>
		public static bool GetMarkDeletedRight(TeamBlack teamBlack, bool triggerException)
		{
			return GetMarkDeletedRight(new GenericModuleDataContext(), teamBlack, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有标记删除TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">标记删除的TeamBlacks对象。</param>
		/// <returns>布尔值表示当前用户是否有标记删除TeamBlacks的权限。</returns>
		public static bool GetMarkDeletedRight(TeamBlack teamBlack)
		{
			if (Users.CurrentUserId.HasValue)
			{
				int total = 0;
				var oprate = GetOperationRight(teamBlack.TeamId, Users.CurrentUserId.Value, ref total);
				if (total > 0)
					return oprate;
			}

			return GetMarkDeletedRight(teamBlack, false);
		}
		#endregion



		#region GetSettingRight
		/// <summary>
		/// 获取当前用户是否有设置TeamBlacks的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="teamBlack">设置的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有设置TeamBlacks的权限。</returns>
		public static bool GetSettingRight(GenericModuleDataContext dc, TeamBlack teamBlack, bool triggerException)
		{
			string userName = Users.CurrentUserName;
			int permissionCode = (int)PermissionCode.Setting;
			bool b = dc.AccessController.GetUserIsHasPermission<TeamBlack>(userName, teamBlack, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, teamBlack, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有设置TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">设置的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有设置TeamBlacks的权限。</returns>
		public static bool GetSettingRight(TeamBlack teamBlack, bool triggerException)
		{
			return GetSettingRight(new GenericModuleDataContext(), teamBlack, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有设置TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">设置的TeamBlacks对象。</param>
		/// <returns>布尔值表示当前用户是否有设置TeamBlacks的权限。</returns>
		public static bool GetSettingRight(TeamBlack teamBlack)
		{
			if (Users.CurrentUserId.HasValue)
			{
				int total = 0;
				var oprate = GetOperationRight(teamBlack.TeamId, Users.CurrentUserId.Value, ref total);
				if (total > 0)
					return oprate;
			}

			return GetSettingRight(teamBlack, false);
		}

		public static bool GetSetEffectiveStateRight(GenericModuleDataContext dc, TeamBlack teamBlack, bool triggerException)
		{
			return GetSettingRight(dc, teamBlack, triggerException);
		}

		public static bool GetSetEffectiveStateRight(TeamBlack teamBlack, bool triggerException)
		{
			return GetSetEffectiveStateRight(new GenericModuleDataContext(), teamBlack, triggerException);
		}

		public static bool GetSetEffectiveStateRight(TeamBlack teamBlack)
		{
			if (Users.CurrentUserId.HasValue)
			{
				int total = 0;
				var oprate = GetOperationRight(teamBlack.TeamId, Users.CurrentUserId.Value, ref total);
				if (total > 0)
					return oprate;
			}
			return GetSetEffectiveStateRight(teamBlack, false);
		}
		#endregion



		#region GetDeleteRight
		/// <summary>
		/// 获取当前用户是否有删除TeamBlacks的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="teamBlack">删除的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有删除TeamBlacks的权限。</returns>
		public static bool GetDeleteRight(GenericModuleDataContext dc, TeamBlack teamBlack, bool triggerException)
		{
			string userName = Users.CurrentUserName;
			int permissionCode = (int)PermissionCode.Delete;
			bool b = dc.AccessController.GetUserIsHasPermission<TeamBlack>(userName, teamBlack, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, teamBlack, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有删除TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">删除的TeamBlacks对象。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有删除TeamBlacks的权限。</returns>
		public static bool GetDeleteRight(TeamBlack teamBlack, bool triggerException)
		{
			return GetDeleteRight(new GenericModuleDataContext(), teamBlack, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有删除TeamBlacks的权限。
		/// </summary>
		/// <param name="teamBlack">删除的TeamBlacks对象。</param>
		/// <returns>布尔值表示当前用户是否有删除TeamBlacks的权限。</returns>
		public static bool GetDeleteRight(TeamBlack teamBlack)
		{
			if (Users.CurrentUserId.HasValue)
			{
				int total = 0;
				var oprate = GetOperationRight(teamBlack.TeamId, Users.CurrentUserId.Value, ref total);
				if (total > 0)
					return oprate;
			}
			return GetDeleteRight(teamBlack, false);
		}
		#endregion



		private static bool GetOperationRight(int teamId, Guid userId, ref int totalCount)
		{
			var operation = false;
			if (!TeamMembers.Exists(userId, null))
			{
				totalCount = 0;
				return operation;
			}
			var ids = GetParentIds(teamId, false);			
			foreach (var id in ids)
			{
				if (TeamMembers.Exists(id))
				{
					var m = TeamMembers.GetLeader(id).UserId;
					if (Users.CurrentUserId.Value == m)
					{
						operation = true;
						break;
					}
				}
			}
			totalCount = ids.Count();
			return operation;
		}
	}





	/// <summary>
	/// TeamBlacks 类后台管理部分。
	/// </summary>
	public static partial class TeamBlacks
	{
		public static bool GetManageListRight()
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			return dc.AccessController.GetUserIsHasPermission<object>(Users.CurrentUserName, null, TeamBlacks.ResourceId, (int)TeamBlacks.PermissionCode.Delete, Sites.CurrentSiteId);
		}

		public struct TeamBlackForManageList
		{
			public int TeamId { get; set; }
			public string TeamName { get; set; }
			public bool IsEffective { get; set; }
			public bool IsDelete { get; set; }
			public DateTime CreateDate { get; set; }
			public Guid? CreatorId { get; set; }
			public string TeamDescribe { get; set; }
			public Guid? GroupLeader { get; set; }
			public int? SiteId { get; set; }
			public int? PTeamId { get; set; }
		}

		public struct TeamBlackUserForManageList
		{
			public int TeamId { get; set; }
			public Guid UserId { get; set; }
			public string UserName { get; set; }
			public string RealName { get; set; }
			public bool IsLeader { get; set; }
			public bool IsEffective { get; set; }
			public int? SiteId { get; set; }
			public int? PTeamId { get; set; }
		}

		public static int[] GetTeamIdsByLeader(Guid leader)
		{
			var returnIds = new List<int>();

			var list = TeamMembers.GetGropuIdsByLeader(leader);
			var ids = "";
			foreach (var id in list)
			{
				ids += (string.IsNullOrEmpty(ids) ? "" : ",") + id.ToString(); 
				ids += (string.IsNullOrEmpty(ids) ? "" : ",") + GetChildrenTeamIds(id);
			}

			if (!string.IsNullOrEmpty(ids))
			{
				var items = ids.Split(",");
				foreach (var item in items)
				{
					var id = IntExtensions.ParseOrNull(item);
					if (!id.HasValue) continue;
					if (returnIds.Contains(id.Value)) continue;
					returnIds.Add(id.Value);
				}
			}
			return returnIds.ToArray();
		}

		/// <summary>
		/// 获取包含本身 子节点id集合 
		/// </summary>
		/// <param name="siteId"></param>
		/// <param name="pTeamId"></param>
		/// <returns></returns>
		public static int[] GetChildrenIds(int pTeamId, bool containSelf)
		{
			var returnIds = new List<int>();
			var ids = GetChildrenTeamIds(pTeamId);
			
			if (!string.IsNullOrEmpty(ids))
			{
				var items = ids.Split(",");
				foreach (var item in items)
				{
					var id = IntExtensions.ParseOrNull(item);
					if (!id.HasValue) continue;
					if (!containSelf)
					{
						if (id.Value == pTeamId) continue;
					}
					if (returnIds.Contains(id.Value)) continue;
					returnIds.Add(id.Value);
				}
			}
			
			return returnIds.ToArray();
		}

		/// <summary>
		/// 获取子集
		/// </summary>
		/// <param name="siteId"></param>
		/// <param name="PTeamId"></param>
		/// <returns></returns>
		private static string GetChildrenTeamIds(int pTeamId)
		{
			var ids = "";
			if (!Exists(pTeamId)) return ids;
			var teamItem = GetItem(pTeamId);
			if (teamItem.ChildrenCount > 0)
			{
				var list = TeamBlacks.GetTeamBlackList(pTeamId, null, "");
				foreach (var li in list)
				{
					var item = GetItem(li.TeamId);
					ids += (string.IsNullOrEmpty(ids) ? "" : ",") + li.TeamId.ToString();
					if (item.ChildrenCount > 0)
						ids += (string.IsNullOrEmpty(ids) ? "" : ",") + GetChildrenTeamIds(li.TeamId);					
				}
			}
			else
				ids += (string.IsNullOrEmpty(ids) ? "" : ",") + pTeamId.ToString();
			return ids;
		}

		/// <summary>
		/// 获取父节点id集合
		/// </summary>
		/// <param name="siteId"></param>
		/// <param name="teamId"></param>
		/// <returns></returns>
		public static int[] GetParentIds(int teamId, bool containSelf)
		{
			var returnIds = new List<int>();
			var ids =  GetParentTeamIds(teamId);

			if (!string.IsNullOrEmpty(ids))
			{
				var items = ids.Split(",");
				foreach (var item in items)
				{
					var id = IntExtensions.ParseOrNull(item);
					if (!id.HasValue) continue;
					if (!containSelf)
					{
						if (id.Value == teamId) continue;
					}
					if (returnIds.Contains(id.Value)) continue;
					returnIds.Add(id.Value);
				}
			}
			return returnIds.ToArray();
		}


		/// <summary>
		/// 获取父集
		/// </summary>
		/// <param name="siteId"></param>
		/// <param name="teamId"></param>
		/// <returns></returns>
		private static string GetParentTeamIds(int teamId)
		{
			var ids = "";
			if (!Exists(teamId)) return ids;
			var teamItem = GetItem(teamId);
			ids += (string.IsNullOrEmpty(ids) ? "" : ",") + teamId.ToString();

			if (teamItem.PTeamId.HasValue)
				ids += (string.IsNullOrEmpty(ids) ? "" : ",") + GetParentTeamIds(teamItem.PTeamId.Value);
			
			return ids;
		}

		private static IQueryable<TeamBlackForManageList> GetListQuery(GenericModuleDataContext dc, int? pTeamId, Guid? leaderId, string keyword)
		{
			var q = from p in dc.TeamBlacks
					where !p.IsDelete
					select new TeamBlackForManageList
					{
						TeamId = p.TeamId,
						TeamName = p.TeamName,
						IsEffective = p.IsEffective,
						CreateDate = p.CreateDate,
						CreatorId = p.CreatorId,
						TeamDescribe = p.TeamDescribe,
						SiteId = p.SiteId,
						PTeamId = p.PTeamId,
						GroupLeader = dc.TeamMembers.SingleOrDefault(u=>u.TeamId == p.TeamId && u.IsLeader).UserId
					};
			if (pTeamId.HasValue)
				q = q.Where(p => p.PTeamId == pTeamId);
			
			if (!string.IsNullOrEmpty(keyword))
				q = q.Where(p => p.TeamName.Contains(keyword));

			return q;
		}


		public static PaginationInfo<List<TeamBlackForManageList>> GetPaginationManageList(int? pTeamId, Guid? leaderId, string keyword, int pageSize, int currentPage)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = GetListQuery(dc, pTeamId, leaderId, keyword);

			var q2 = q.ToList();

			if (leaderId.HasValue)			
			{
				var groupIds = GetTeamIdsByLeader(leaderId.Value);
				q2 = groupIds.SelectMany(id => q.Where(p => p.TeamId == id)).ToList();
			}

			PaginationInfo<List<TeamBlackForManageList>> pageInfo = new PaginationInfo<List<TeamBlackForManageList>>();
			pageInfo.PageSize = pageSize;
			pageInfo.CurrentPage = currentPage;
			pageInfo.RecordCount = q2.Count();
			pageInfo.Records = q2.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
			return pageInfo;
		}

		public static List<TeamBlackForManageList> GetTeamBlackList(int? pTeamId, Guid? leaderId, string keyword)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = GetListQuery(dc, pTeamId, leaderId, keyword);

			return q.ToList();
		}


		public static List<TeamBlackUserForManageList> GetGroupUserList(int? teamId, Guid? leaderId, bool? isEffective)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = from p2 in dc.TeamMembers
					from p in dc.TeamBlacks
					from p3 in dc.Users
					where p2.UserId == p3.UserId && p2.TeamId == p.TeamId && !p.IsDelete
					orderby p2.IsLeader descending
					select new TeamBlackUserForManageList
					{
						TeamId = p2.TeamId,
						UserId = p2.UserId,
						UserName = p3.UserName,
						IsLeader = p2.IsLeader,
						IsEffective = p.IsEffective,						
						PTeamId = p.PTeamId
					};		

			if (teamId.HasValue)
				q = q.Where(p => p.TeamId == teamId.Value);			

			if (isEffective.HasValue)
				q = q.Where(p => p.IsEffective == isEffective.Value);			

			if (leaderId.HasValue)
			{
				var groupIds = GetTeamIdsByLeader(leaderId.Value);
				return groupIds.SelectMany(id => q.Where(p => p.TeamId == id)).ToList();
			}
			return q.ToList();
		}
	}
}